package messagepasser;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

public class ResendTask extends TimerTask {
	private MessagePasser myPasser;
	private Timer myTimer;
	private TimeStampedMessage mesg;
	
	public ResendTask(MessagePasser passer, Timer t, TimeStampedMessage message) {
		myPasser = passer;
		myTimer = t;
		mesg = message;
	
	}
	
	public void run() {
		synchronized (myPasser) {
			if (myPasser.isExpecting(mesg)) {
				myTimer.cancel();
				myPasser.getHbQ().remove(mesg);
			
				
				for(String lhs : mesg.getSequenceNumber().keySet()) {
					if (myPasser.getSequenceNumber().get(lhs).intValue() < mesg.getSequenceNumber().get(lhs).intValue()) {
						myPasser.getSequenceNumber().put(lhs, new Integer(mesg.getSequenceNumber().get(lhs)));
					}
				}		
				myPasser.getSequenceNumber().put(mesg.getOrgSender(), mesg.getSeqNo());
				
				
			}
			
			if (myPasser.isNextToExpecting(mesg)) {
							
					myTimer.cancel();
					myPasser.getHbQ().remove(mesg);
				
					for(String lhs : mesg.getSequenceNumber().keySet()) {
						if (myPasser.getSequenceNumber().get(lhs).intValue() < mesg.getSequenceNumber().get(lhs).intValue()) {
							myPasser.getSequenceNumber().put(lhs, new Integer(mesg.getSequenceNumber().get(lhs)));
						}
					}		
					myPasser.getSequenceNumber().put(mesg.getOrgSender(), mesg.getSeqNo());
					myPasser.clearOutdatedHbQ(mesg);
				
			}
			
		}
		myTimer.cancel();
	}
}
